package	com.sdry.web.controller.plan;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.sdry.model.lz.Materiel;
import com.sdry.model.plan.Bom;
import com.sdry.model.plan.BomDetail;
import com.sdry.model.plan.Product;
import com.sdry.service.plan.BomDetailService;
import com.sdry.service.plan.BomService;
import com.sdry.service.plan.ProductService;
import com.sdry.service.plan.StorageAreaService;
import com.sdry.utils.ExcelUtils;
import com.sdry.utils.ResponseUtil;
/**
 *
 *@ClassName: BomController
 *@Description: BOM
 *@Author tdd
 *@Date 2019-07-03 09:47:21
 *@version 1.0
*/
@Controller
@RequestMapping("/bom")
public class BomController {
	@Resource BomService bomService;
	@Resource ProductService productService;
	@Resource BomDetailService bomDetailService;
	@Resource StorageAreaService storageAreaService;
	@RequestMapping("/page")
	public String bom(Model model){
		Product param = new Product();
		List<Product> products = productService.queryAllByMution(param );
		model.addAttribute("products",products);
		return "/plan/bom";
	}
	/** 
	 * 根据主键id查询实体
	 * @param id 主键id
	 * @return 实体
	*/
	@RequestMapping("/queryById")
	@ResponseBody
	public Bom queryById(Long id) {
		Bom param = bomService.queryById(id);
		return param;
	}
	/** 
	 * 条件查询所有
	 * @param param 实体条件
	 * @return 实体集合
	*/
	@RequestMapping("/queryAllByMution")
	@ResponseBody
	public List<Bom> queryAllByMution(Bom param) {
		List<Bom> list = bomService.queryAllByMution(param);
		return list;
	}
	/** 
	 * 条件分页查询
	 * @param param 实体条件
	 * @param response
	 * @throws Exception
	*/
	@RequestMapping("/list")
	public void list(Bom param,HttpServletResponse response){
		/*
		 * 条件分页查询内容
		 */
		List<Bom> list = bomService.findPageByMution(param);
		/*
		 * 条件查询总条数
		 */
		Integer total = bomService.selectCountByMution(param);
		/*
		 * 转为json数据传至页面
		 */
		//创建result
		JSONObject jsonObject = new JSONObject();
		//添加入jsonObject
		jsonObject.put("code", 0);
		jsonObject.put("rows", list);
		jsonObject.put("total", total);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/** 
	 * 插入返回id
	 * @param param 实体条件
	 * @param response
	 * @throws Exception
	*/
	@RequestMapping("/insert")
	public void insert(Bom param,Long[] wid,int[] quantity, HttpServletResponse response){
		param.setState("0");
		Long id = bomService.insert(param);
		int fig = 0;
		if(null != id){
			BomDetail bomDetail = new BomDetail();
			bomDetail.setBomId(id);
			for (int i = 0; i < wid.length; i++) {
				bomDetail.setMaterielId(wid[i]);
				bomDetail.setQuantity(quantity[i]);
				bomDetailService.insert(bomDetail);
			}
			fig = 1;
		}
		try {
			ResponseUtil.write(response,fig);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/** 
	 * 根据主键更新 返回影响行数
	 * @param param 实体条件
	 * @param response
	 * @throws Exception
	*/
	@RequestMapping("/update")
	public void update(Bom param,Long[] wid,int[] quantity,HttpServletResponse response){
		Integer count = bomService.update(param);
		int fig = 0;
		if(count > 0){
			bomDetailService.deleteByBomId(param.getId()+"");
			BomDetail bomDetail = new BomDetail();
			bomDetail.setBomId(param.getId());
			for (int i = 0; i < wid.length; i++) {
				bomDetail.setMaterielId(wid[i]);
				bomDetail.setQuantity(quantity[i]);
				bomDetailService.insert(bomDetail);
			}
			fig = 1;
		}
		try {
			ResponseUtil.write(response,fig);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/** 
	 * 根据主键拼接的字符串删除返回影响行数
	 * @param ids 主键拼接的字符串
	 * @return 影响行数
	*/
	@RequestMapping("/delete")
	public void delete(String ids,HttpServletResponse response){
		ids=ids.replace("'",""); 
		Integer count = bomService.delete(ids);
		if(count > 0){
			bomDetailService.deleteByBomId(ids);
		}
		try {
			ResponseUtil.write(response,count);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/** 
	 * 修改启用状态返回影响行数
	 * @param ids 主键拼接的字符串
	 * @return 影响行数
	 */
	@RequestMapping("/upState")
	public void upState(Bom param,HttpServletResponse response){
		Integer count = bomService.upStateByProductId(param.getProductId()+"", "0");
		if(count > 0){
			bomService.upStateById(param.getId()+"", "1");
		}
		try {
			ResponseUtil.write(response,count);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 导入线边库
	 * @param file	上传的文件
	 * @param response
	 */
	@RequestMapping(value="/upload", method = RequestMethod.POST)
    @ResponseBody
	public void upload(@RequestParam(value="file",required=false) MultipartFile file, HttpServletRequest request, HttpServletResponse response){
	    String savePath = "";
		// 1.获取原文件名1
        String fileName = file.getOriginalFilename();
		// 2.获取要保存的路径文件夹1
		String realPath = request.getSession().getServletContext().getRealPath("/uploadFile/");
		// 3.保存
		savePath = realPath + "\\" + fileName;
		File desFile = new File(savePath);
		try {
			//把文件内容存入
			file.transferTo(desFile);
			//取文件后缀
			String subfix = fileName.lastIndexOf(".")==-1? "" : fileName.substring(fileName.lastIndexOf(".")+1);
			List<List<String>> lists = new ArrayList<>();
			//获取导入列数
			int num = 20;
			//用工具类读取导入的文件
			if(subfix.equals("xls")){
				lists = ExcelUtils.readXls(savePath, request, num);
			}else if(subfix.equals("xlsx")){
				lists = ExcelUtils.readXlsx(savePath, request, num);
			}
			Materiel m = new Materiel();
			Product product = new Product();
			Bom b = new Bom();
			BomDetail bd = new BomDetail();
			Long affact = 0L;
			Long bid = 0L;
			int flag = 1;
	        //获取每一行要导入的数据，存入线边库
	        List<String> list = new ArrayList<>();
	        for (int i = 0; i < lists.size(); i++) {
	            list= lists.get(i);
	            if(i == 0){
	            	product.setProductName(list.get(1));
	            	product.setProductNumber(list.get(0));
		            Long pid = productService.queryIdByMution(product);
		            b.setProductId(pid);
		            b.setVersion(list.get(2));
		            b.setState(0+"");
		            bid = bomService.insert(b);
	            }else{
	            	m.setMateriel_name(list.get(1));
	            	m.setMateriel_num(list.get(0));
		            Long mid = storageAreaService.findMaterielByNameAndNum(m);
		            bd.setMaterielId(mid);
		            bd.setBomId(bid);
		            bd.setQuantity(Integer.parseInt(list.get(2)));
		            affact = bomDetailService.insert(bd);
		            if(affact <= 0){
		            	flag = 0;
		            	break;
		            }
	            }
	        }
			ResponseUtil.write(response, flag);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
